package com.qf.leadnewswemedia.controller.v1;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.leadnewsmodel.dtos.PageResponseResult;
import com.qf.leadnewsmodel.dtos.ResponseResult;
import com.qf.leadnewsmodel.enums.AppHttpCodeEnum;
import com.qf.leadnewsutils.commons.ThreadLocalUtil;
import com.qf.leadnewswemedia.model.dtos.MaterialPageRequestDto;
import com.qf.leadnewswemedia.model.pojos.WmMaterial;
import com.qf.leadnewswemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/v1/material")
public class WmMaterialController {

    @Autowired
    private WmMaterialService materialService;

    @PostMapping("/list")
    public ResponseResult list(@RequestBody MaterialPageRequestDto pageRequestDto){
        //分页参数健壮性判断
        pageRequestDto.checkParam();

        IPage<WmMaterial> page = new Page<>(pageRequestDto.getPage(),pageRequestDto.getSize());
        LambdaQueryWrapper<WmMaterial> qw = new LambdaQueryWrapper<>();

        //登录用户
        Long uid = ThreadLocalUtil.getUid();
        if (uid == null || uid == 0){
            //没登陆
            return PageResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //设置用户id做为查询条件
        qw.eq(WmMaterial::getUserId,uid);

        //是否收藏
        Integer isCollection = pageRequestDto.getIsCollection();
        if (isCollection == null){
            //没有传这个值，默认查询全部
            isCollection = 0;
        }
        if (isCollection != 0) {
            qw.eq(WmMaterial::getIsCollection, isCollection);
        }

        //按照创建时间降序排列(最新添加的在前面)
        qw.orderByDesc(WmMaterial::getCreatedTime);

        //mybatisplus的分页查询方法
        materialService.page(page,qw);

        //当前页码
        long current = page.getCurrent();
        //每页多少条
        long size = page.getSize();
        //总记录数
        long total = page.getTotal();
        //查询到的数据记录
        List<WmMaterial> records = page.getRecords();

        PageResponseResult pageResponseResult = new PageResponseResult(current,size,total);
        pageResponseResult.setData(records);

        return pageResponseResult;
    }

    /**
     * 需要通过统一的异常处理器，统一处理异常信息
     * @param multipartFile
     * @return
     * @throws Exception
     */
    @PostMapping("/upload_picture")
    public ResponseResult uploadPic(MultipartFile multipartFile) throws Exception {
        return materialService.uploadPic(multipartFile);
    }
}
